﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ECI.CommonLibrary;
using System.Data;
using System.Web;
using ECI.Entities;
using ECI.Controls;
using ECI.CoreLibrary;
using ECI.WebLib.Data;
using System.Web.UI;
using ECI.BaseLanguage;

namespace ECI.DynamicData.ElementBuilder
{
    public class TDropdownList : IElement
    {
        private ECIDropDownList cboList = null;
        public override void Create(ElementParameter param)
        {
            this.Init(param);

            this.CreateContainer();

            cboList = new ECIDropDownList();
            if (string.IsNullOrEmpty(param.Field.DropdownlistConfig))
            {
                //自定义的下拉框配置
                DataTable data = null;
                if (string.IsNullOrEmpty(param.Field.DictionaryTypeConfig))
                {
                    #region 自定义配置
                    string sql = "SELECT " + param.Field.JoinTableField + ",";
                    if (string.IsNullOrEmpty(param.Field.JoinShowField))
                    {
                        sql += param.Field.JoinTableField;
                    }
                    else
                    {
                        sql += param.Field.JoinShowField;
                    }

                    sql += " FROM  " + param.Field.JoinTable;

                    if (!string.IsNullOrEmpty(param.Field.JoinCondition))
                    {
                        sql += " WHERE " + param.Field.JoinCondition;
                    }

                    if (!string.IsNullOrEmpty(param.Field.JoinSortConfig))
                    {
                        sql += " ORDER BY " + param.Field.JoinSortConfig;
                    }
                    data = DBHelper.GetDataTable(sql);

                    cboList.DataValueField = data.Columns[0].ColumnName;
                    cboList.DataTextField = data.Columns[1].ColumnName;
                    cboList.DataSource = data;
                    cboList.DataBind();
                    #endregion
                }
                else
                {
                    #region  标准配置
                    //通过选择配置出来
                    cboList.ECIType = Field.DictionaryTypeConfig;
                    cboList.AutoBind = false;
                    cboList.BindDataAuto("");
                    #endregion
                }
            }
            else
            {
                DataTable table = new DataTable();
                table.Columns.Add("CODE");
                table.Columns.Add("NAME");
                string[] array = param.Field.DropdownlistConfig.Split(',');
                foreach (string item in array)
                {
                    string[] itemArray = item.Split('|');
                    string code = itemArray[0].Trim();
                    string name = "";
                    if (itemArray.Length == 0)
                    {
                        name = code;
                    }
                    else
                    {
                        name = itemArray[1].Trim();
                    }

                    table.Rows.Add(new object[] { code, name });
                }

                cboList.DataValueField = table.Columns[0].ColumnName;
                cboList.DataTextField = table.Columns[1].ColumnName;
                cboList.DataSource = table;
                cboList.DataBind();
            }

            if (param.query == "select")
            {
                if (param.Field.QueryAddEmpty.ToMyString() == "1")
                {
                    cboList.Items.Insert(0, new ListItem("-" + Lang.A00235.Read() + "-", "DBNull"));//要区分是查询 还是编辑 编辑就空
                }
                cboList.Items.Insert(0, new ListItem("-" + Lang.A00044.Read() + "-", ""));//要区分是查询 还是编辑 编辑就空
            }
            else
            {
                cboList.Items.Insert(0, new ListItem("", ""));
            }

            cboList.Attributes.Add("sql", param.Field.SqlAttribute);
            cboList.Attributes.Add("mainalias", param.Field.MainAlias);


            if (param.type == "Edit")
            {
                if (param.Field.ControlWidth.Length > 0)
                {
                    cboList.Style["width"] = param.Field.ControlWidth;
                }
                else
                {
                    cboList.Style["width"] = "85%";//占整个单元格的85%
                }
            }
            else
            {
                cboList.Style["width"] = "85%";//占整个单元格的85%
            }

            cboList.ID = "txt" + param.Field.Name;

            if (param.EditMode == "BatchUpdate") cboList.ID = "txtBatch" + param.Field.Name;

            //if (param.type == "Edit") DynamicQuery.EditLockControl(cboList, param.DataRow, param.Field, param.EditMode);//会根据是否新增 编辑状态动态显示编辑模式
            //if (param.type == "Edit") DynamicQuery.EditDefaultControl(cboList, param.DataRow, param.Field);//显示默认值

            //if (param.type == "Edit" && param.Field.SystemData.ToMyString() != "") DynamicQuery.LockControl(cboList);//系统字段锁定
            //if (param.type == "Edit") DynamicQuery.CascadeControl(cboList, param.DataRow, param.Field);
            //if (param.type == "Edit") DynamicQuery.EditSystemFieldShowValue(cboList, param.DataRow, param.Field);//系统字段-是否在新增时就显示


            if (param.type == "Edit" && DynamicQuery.EditHideForSystemField(param.Field))
            {
                param.HideCell.Controls.Add(cboList);
            }
            else if (param.Field.Hidden == "Y")
            {
                param.HideCell.Controls.Add(cboList);
            }
            else
            {
                if (Field.AfterElement != "")
                {
                    TableCell cell = this.GetControlCell(param.TableRow.Parent as Table, Field.AfterElement);
                    if (cell == null)
                        throw new Exception(Field.MainAlias + ": 没找到上级元素" + Field.AfterElement);
                    cell.Controls.Add(cboList);
                }
                else
                {
                    MyTableCell.Controls.Add(cboList);
                    param.TableRow.Cells.Add(MyTableCell);
                }
            }


            //在赋值之前 如果是被级联的下拉框 则要加载数据



            if (param.DataRow != null)
            {
                string value = GetDataValueForEditPage();
                cboList.SelectedValue = value;
            }


            #region 复制新增时 是否清除控件内容
            if (param.Field.CopyRemoveData.ToMyString() == "1" && param.EditMode.ToLower() == "copy")
            { 
                if (this.Field.DataSource.Length > 0)
                    cboList.SelectedValue = GetDataValueForEditPage();
                else
                      cboList.SelectedValue = Field.DefaultValue;

            }
            #endregion

            //注册客户端事件
            ClientEventRegister();

            //注册级联下来框事件
            if (this.Field.NextDdlTarget.Trim().Length > 0)
            {
                cboList.AutoPostBack = true;
                ElementEvent.DropdownListEvent ddlEvent = new ECI.DynamicData.ElementEvent.DropdownListEvent(param);
                cboList.SelectedIndexChanged += new EventHandler(ddlEvent.DropdownList_SelectedIndexChanged);
            }
        }



        #region IElement 成员
        public override void Locked()
        {
            DataRow dataRow = param.DataRow;
            string editMode = param.EditMode;

            if (Field.EditLockMode == "LOCKFULL") LockControl();
            else if (dataRow != null && editMode.ToLower() != "copy" && Field.EditLockMode == "LOCKEDIT") LockControl();
            else if (dataRow == null && Field.EditLockMode == "LOCKADD") LockControl();
        }

        public override void Default()
        {
            DataRow dataRow = param.DataRow;
            string editMode = param.EditMode;

            if (string.IsNullOrEmpty(Field.DefaultValue) == false && dataRow == null)
            {
                ListItem item = cboList.Items.FindByValue(this.GetDefaultDataForControl());
                //if (item == null) throw new Exception("字段" + Field.MainAlias + ":" + Field.Name + "设置的默认值错误!<br>设置值:" + Field.DefaultValue + "不在下拉框数据项中!");
                if (item == null) throw new Exception("字段" + Field.MainAlias + ":" + Field.Name + Lang.A00088.Read() + ":" + Field.DefaultValue + Lang.A00089.Read());
                item.Selected = true;
                cboList.SaveInHideField();
            }
        }

        public override void SystemField()
        {
            cboList.Enabled = false;
            cboList.BackColor = System.Drawing.Color.Gainsboro;
            DataRow dataRow = param.DataRow;

            if (Field.SystemData.ToMyString() != "" && Field.SystemDataTrigger.ToMyString() == "INSERT" && Field.SystemDataShow.ToMyString() == "1" && dataRow == null)
            {
                cboList.SelectedValue = this.GetSystemDataValue();
            }
        }

        public override void Cascade()
        {
            DataRow dataRow = param.DataRow;
            string editMode = param.EditMode;

            //新增的情况下才执行
            if (dataRow == null)
            {
                string value = PageHelper.Request(Field.Name);
                if (value != "")
                {
                    cboList.SelectedValue = value;
                }
            }
        }
        #endregion

        private void LockControl()
        {
            cboList.Enabled = false;
            cboList.BackColor = System.Drawing.Color.Gainsboro;
        }


        public override string GetValue()
        {
            if (EditMode == DynamicEditMode.BatchUpdate)
            {
                CheckBox chk = param.Table.FindControl("chk" + Field.Name) as CheckBox;
                if (chk.Checked)
                {
                    DropDownList txtBox = param.Table.FindControl("txtBatch" + Field.Name) as DropDownList;
                    string value = txtBox.SelectedValue;
                    return DynamicQuery.GetDynamicSQL(Field, value, DynamicEditMode.Update);
                }
                else
                {
                    return "";
                }
            }
            else
            {
                DropDownList txtBox = param.Table.FindControl("txt" + Field.Name) as DropDownList;
                string value = "";
                if (Field.SystemData.ToMyString() == "")
                {
                    value = txtBox.SelectedValue;
                }
                else
                {
                    value = this.GetSystemDataValue();
                }

                return DynamicQuery.GetDynamicSQL(Field, value, EditMode);
            }

        }

        public override void DataKeep()
        {
            if (PageHelper.CurrentPage.IsPostBack)
            {
                if (param.Field.DataKeep == "Y" && param.Field.NotSave == "Y")
                {
                    string value = "";
                    object obj = PageHelper.CurrentPage.Request["txt" + param.Field.Name];
                    if (obj != null)
                    {
                        value = PageHelper.Request("txt" + param.Field.Name);
                    }
                    else
                    {
                        value = PageHelper.Request("txt" + param.Field.Name + "_hid");
                    }

                    this.cboList.SelectedValue = value;
                }
            }
        }

        public override void QueryDefault()
        {
            if (Field.DefaultValueQuery != "" && param.type.ToLower() == "query")
            {
                if (Field.DefaultValueQuery != "" && param.type.ToLower() == "query")
                {
                    cboList.SelectedValue = Field.DefaultValueQuery;
                }
            }

            if (Field.Udf6 == "Y")
                LockControl();

        }

        public override void ClientEventRegister()
        {
            DataRow dataRow = param.DataRow;
            string editMode = param.EditMode;
            if (Field.EventConfig.Length > 0)
            {
                string[] array = Field.EventConfig.Split('|');
                foreach (string item in array)
                {
                    string[] eventConfig = item.Split('#');
                    if (eventConfig.Length < 2) throw new Exception(Lang.A00087.Read() + "【" + Field.MainAlias + "】" + Lang.A00229.Read());//字段【" + Field.MainAlias + "】注册事件不正确
                    string eventType = eventConfig[0];
                    string eventContent = eventConfig[1];
                    this.cboList.Attributes.Add(eventType, eventContent);
                }
            }
        }

        public override string GetRealValue()
        {
            throw new NotImplementedException();
        }
    }
}
